package com.rc.saas.tenant.controller.acct;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.rc.saas.tenant.base.BaseSearch;
import com.rc.saas.tenant.base.WebPageInfo;
import com.rc.saas.tenant.common.utils.BeanUtil;
import com.rc.saas.tenant.common.utils.StringUtil;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.component.UploadImg;
import com.rc.saas.tenant.config.UpYunConfig;
import com.rc.saas.tenant.model.acct.*;
import com.rc.saas.tenant.model.operator.TenantOperator;
import com.rc.saas.tenant.model.operator.TenantOperatorStation;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.search.acct.*;
import com.rc.saas.tenant.search.operator.OperatorSearch;
import com.rc.saas.tenant.search.order.OrderSearch;
import com.rc.saas.tenant.search.tenant.TenantOperatorAccountRecordSearch;
import com.rc.saas.tenant.service.acct.*;
import com.rc.saas.tenant.service.operator.TenantOperatorService;
import com.rc.saas.tenant.service.operator.TenantOperatorStationService;
import com.rc.saas.tenant.shiro.ShiroUtils;
import com.rc.saas.tenant.transfers.alipay.AliPayWalletService;
import com.rc.saas.tenant.transfers.alipay.vo.AlipayTransPayWalletVo;
import com.rc.saas.tenant.upyun.WebUploader;
import com.rc.saas.tenant.util.ExportUtils;
import com.rc.saas.tenant.vo.acct.*;
import com.rc.saas.tenant.vo.elec.ElecStationResult;
import com.rc.saas.tenant.vo.operator.OperatorElecStationVo;
import com.rc.saas.tenant.vo.order.OrderPrintVo;
import com.rc.saas.tenant.vo.order.OrderResult;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.weixin4j.pay.util.SHA1;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author frog
 * @date 2021/1/12
 */
@Controller
@RequestMapping("/acctTenantOperator")
public class AcctTenantOperatorController {

    private static Logger logger = LogManager.getLogger(AcctTenantOperatorController.class);


    @Autowired
    private UploadImg uploadImg;

    @Autowired
    private UpYunConfig upYunConfig;

    @Autowired
    @Lazy
    private TenantOperatorService tenantOperatorService;

    @Autowired
    private AcctBankService acctBankService;

    @Autowired
    @Lazy
    private AcctBillOrderService acctBillOrderService;

    @Autowired
    private TenantOperatorStationService tenantOperatorStationService;

    @Autowired
    private AcctContractService acctContractService;

    @Autowired
    private AcctRuleService acctRuleService;

    @Autowired
    private AcctRuleRepositoryService acctRuleRepositoryService;

    @Autowired
    private AcctWithdrawApplyService acctWithdrawApplyService;

    @Autowired
    private TenantOperatorAccountService tenantOperatorAccountService;

    @Autowired
    private TenantOperatorAccountRecordService tenantOperatorAccountRecordService;

    @Autowired
    private AliPayWalletService aliPayWalletService;

    @Autowired
    private AcctWithdrawInvoiceService acctWithdrawInvoiceService;

    @Autowired
    private AcctSubItemService acctSubItemService;

    @Autowired
    private TenantOperatorAcctSettingService tenantOperatorAcctSettingService;

    /**
     * 跳转分销商列表(结算中心)
     *
     * @return
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/templates/acct/acctTenantOperator";
    }


    /**
     * 跳转分销商列表(结算中心分销商入口)
     *
     * @return
     */
    @RequestMapping(value = "/operatorIndex", method = RequestMethod.GET)
    public String operatorIndex(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(tenantUser.getTenantOperatorCode());
        List<AcctBank> acctBankList = acctBankService.selectByTenantOperatorCode(tenantUser.getTenantOperatorCode());
        List<ElecStationResult> elecStationResultList = tenantOperatorStationService.listElecStationByTenantOperator(tenantUser.getTenantOperatorCode());
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("acctBankList", acctBankList);
        model.addAttribute("elecStationResultList", elecStationResultList);
        return "/templates/acct/acctDetailOperator";
    }


    /**
     * 返回分销商列表(结算中心)数据
     *
     * @return
     */
    @RequestMapping(value = "/listPageAcctTenantOperator", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctTenantOperator(OperatorSearch search) {
        PageInfo<TenantOperator> pageInfo = tenantOperatorService.listPageTenantOperator(search);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转分销商桩群列表(结算中心)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctTenantOperatorElecStation/{tenantOperatorCode}", method = RequestMethod.GET)
    public String operatorElecStation(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/acct/acctTenantOperatorElecStation";
    }

    /**
     * 获取分销商桩群列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctTenantOperatorElecStation", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctTenantOperatorElecStation(AcctTenantOperatorElecStationSearch acctTenantOperatorElecStationSearch) {
        PageInfo<OperatorElecStationVo> pageInfo = tenantOperatorService.listPageAcctTenantOperatorElecStation(acctTenantOperatorElecStationSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转分销商结算规则列表页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctRuleList/{operatorStationId}", method = RequestMethod.GET)
    public String acctRuleList(@PathVariable("operatorStationId") Long operatorStationId, Model model) {
        model.addAttribute("operatorStationId", operatorStationId);
        return "/templates/acct/acctRuleList";
    }


    /**
     * 停用分销商结算规则
     */
    @ResponseBody
    @RequestMapping(value = "/updateAcctRuleStatus", method = RequestMethod.POST)
    public TResponse updateAcctRuleStatus(Long acctRuleId) {
        try {
            AcctRule acctRule = new AcctRule();
            acctRule.setAcctRuleId(acctRuleId);
            acctRule.setStatus("1");
            logger.info("停用分销商结算规则ID:{}", acctRuleId);
            acctRuleService.updateByPrimaryKeySelective(acctRule);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("停用分销商结算规则失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 获取分销商结算规则列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctRule", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctRule(AcctRuleSearch acctRuleSearch) {
        PageInfo<AcctRuleResultVo> pageInfo = acctRuleService.listPageAcctRule(acctRuleSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 判断是否存在进行中的结算规则
     *
     * @return
     */
//    @RequestMapping(value = "/isExecuteAcctRule", method = RequestMethod.GET)
//    @ResponseBody
//    public TResponse isExecuteAcctRule(AcctRuleSearch acctRuleSearch) {
//        try {
//            Boolean executeAcctRule = acctRuleService.isExecuteAcctRule(acctRuleSearch);
//            if (executeAcctRule) {
//                return TResponse.FAIL("存在未开始结算规则，无法新增");
//            }
//            return TResponse.SUCCESS();
//        } catch (Exception e) {
//            logger.error("查询失败", e);
//            return TResponse.FAIL("操作失败");
//        }
//    }

    /**
     * 跳转新增分销商结算规则
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addAcctRule/{operatorStationId}", method = RequestMethod.GET)
    public String addAcctRule(@PathVariable("operatorStationId") Long operatorStationId, Model model) {
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectByPrimaryKey(operatorStationId);
        //查出最后一个规则的规则结束生效时间
        AcctRuleExample example = new AcctRuleExample();
        example.createCriteria().andStatusEqualTo("0").andOperatorStationIdEqualTo(operatorStationId);
        example.setOrderByClause("rule_end_time desc");
        List<AcctRule> acctRules=acctRuleService.selectByExample(example);
        if (!CollectionUtils.isEmpty(acctRules)){
            AcctRule acctRule = acctRuleService.selectByExample(example).get(0);
            model.addAttribute("acctRule", acctRule);
        } else {
            model.addAttribute("acctRule",null);
        }
        model.addAttribute("tenantOperatorStation", tenantOperatorStation);
        return "/templates/acct/addAcctRule";
    }

    /**
     * 跳转编辑分销商结算规则
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/editAcctRule/{acctRuleId}", method = RequestMethod.GET)
    public String editAcctRule(@PathVariable("acctRuleId") Long acctRuleId, Model model) {
        AcctRuleResultVo acctRule = acctRuleService.selectAcctRule(acctRuleId);
        List<AcctRuleRepository> acctRuleRepositories = acctRuleRepositoryService.listRepositoryByTenantCode(acctRule.getTenantCode(), "");
        AcctSubItemExample example = new AcctSubItemExample();
        example.createCriteria().andAcctRuleIdEqualTo(acctRule.getAcctRuleId());
        List<AcctSubItem> acctSubItems = acctSubItemService.selectByExample(example);
        if (acctSubItems != null && acctSubItems.size() > 0) {
            model.addAttribute("acctSubItems", acctSubItems);
        } else {
            model.addAttribute("acctSubItems", null);
        }
        model.addAttribute("acctRule", acctRule);
        model.addAttribute("AcctRuleRepository", acctRuleRepositories);
        return "/templates/acct/editAcctRule";
    }

    /**
     * 跳转编辑分销商结算规则
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctRule/{acctRuleId}", method = RequestMethod.GET)
    public String detailAcctRule(@PathVariable("acctRuleId") Long acctRuleId, Model model) {
        AcctRuleResultVo acctRule = acctRuleService.selectAcctRule(acctRuleId);
        List<AcctRuleRepository> acctRuleRepositories = acctRuleRepositoryService.listRepositoryByTenantCode(acctRule.getTenantCode(), "");
        model.addAttribute("acctRule", acctRule);
        model.addAttribute("AcctRuleRepository", acctRuleRepositories);
        return "/templates/acct/detailAcctRule";
    }


    /**
     * 保存分销商结算规则
     *
     * @return
     */
    @RequestMapping(value = "/saveAcctRule", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctRule(AcctRuleSaveVo acctRuleSaveVo) {
        try {
            if (acctRuleSaveVo.getRuleStartTime() == null || acctRuleSaveVo.getRuleEndTime() == null) {
                return TResponse.FAIL("请输入正确的参数");
            }
            Boolean executeAcctRule = acctRuleService.isProcessingAcctRule(acctRuleSaveVo.getAcctRuleId(), acctRuleSaveVo.getOperatorStationId(), acctRuleSaveVo.getRuleStartTime(), acctRuleSaveVo.getRuleEndTime());
            if (executeAcctRule) {
                return TResponse.FAIL("该时间段内存在进行中的规则,请重新设置");
            }
            acctRuleService.saveAcctRule(acctRuleSaveVo);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商结算规则失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存分销商结算规则模板
     *
     * @return
     */
    @RequestMapping(value = "/saveAcctRuleRepository", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctRuleRepository(AcctRuleRepository acctRuleRepository) {
        try {
            if (acctRuleRepository.getRuleRepositoryId() != null) {
                acctRuleRepositoryService.updateByPrimaryKeySelective(acctRuleRepository);
            } else {
                acctRuleRepositoryService.insertSelective(acctRuleRepository);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商结算规则模板失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除分销商结算规则模板
     *
     * @return
     */
    @RequestMapping(value = "/deleteAcctRuleRepository", method = RequestMethod.POST)
    @ResponseBody
    public TResponse deleteAcctRuleRepository(Long ruleRepositoryId) {
        try {
            acctRuleRepositoryService.deleteByPrimaryKey(ruleRepositoryId);
            logger.info("删除分销商结算规则模板:{ruleRepositoryId}");
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除分销商结算规则模板失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 获取分销商结算规则模板
     *
     * @return
     */
    @RequestMapping(value = "/listAcctRuleRepository", method = RequestMethod.POST)
    @ResponseBody
    public TResponse listAcctRuleRepository(Long operatorStationId, Long acctRuleId, @RequestParam(value = "ruleName", required = false) String ruleName) {
        try {
            TenantUser tenantUser = ShiroUtils.getSessionUser();
            AcctRuleRepositoryResultVo acctRuleRepositoryResultVo = acctRuleRepositoryService.listAcctRuleRepository(tenantUser.getTenantCode(), acctRuleId, ruleName);
            return TResponse.SUCCESS_DATA(acctRuleRepositoryResultVo);
        } catch (Exception e) {
            logger.error("获取分销商结算规则模板失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存分销商提现账户信息
     *
     * @return
     */
    @RequestMapping(value = "/saveAcctBank", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctBank(AcctBankSaveVo acctBankSaveVo) {
        try {
            if ("1".equals(acctBankSaveVo.getWithdrawType())) {
                acctBankSaveVo.setAcctBank(acctBankSaveVo.getBank());
                acctBankSaveVo.setAcctBankAccount(acctBankSaveVo.getAccountNumber());
                acctBankSaveVo.setAccountName(acctBankSaveVo.getUserName());
            } else {
                acctBankSaveVo.setAlipayUserId(acctBankSaveVo.getAccountNumber());
                acctBankSaveVo.setAlipayUserName(acctBankSaveVo.getUserName());
            }

            if (acctBankSaveVo.getAcctBankId() != null) {
                acctBankService.updateByPrimaryKeySelective(acctBankSaveVo);
            } else {
                acctBankService.insertSelective(acctBankSaveVo);
            }
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商提现账户信息失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转分销商银行卡列表(结算中心)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctBank/{tenantOperatorCode}", method = RequestMethod.GET)
    public String acctBank(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/acct/acctBank";
    }

    /**
     * 获取分销商银行卡列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctBank", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctBank(AcctBankSearch acctBankSearch) {
        PageInfo<AcctBankResultVo> pageInfo = acctBankService.listPageAcctBank(acctBankSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }

    /**
     * 跳转分销商收益明细(总览)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctBillOrder", method = RequestMethod.GET)
    public String acctBillOrder(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        List<TenantOperator> tenantOperatorList = tenantOperatorService.listOperatorByTenantCode(tenantUser.getTenantCode());
        model.addAttribute("tenantOperatorList", tenantOperatorList);
        return "/templates/acct/acctBillOrderTotal";
    }

    /**
     * 跳转分销商收益明细
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctBillOrder/{tenantOperatorCode}", method = RequestMethod.GET)
    public String acctBillOrder(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        List<ElecStationResult> elecStationList = tenantOperatorStationService.listElecStationByTenantOperator(tenantOperatorCode);
        model.addAttribute("elecStationList", elecStationList);
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/acct/acctBillOrder";
    }


    /**
     * 跳转分销商收益明细
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctBillOrderOperator/{tenantOperatorCode}", method = RequestMethod.GET)
    public String acctBillOrderOperator(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        List<ElecStationResult> elecStationList = tenantOperatorStationService.listElecStationByTenantOperator(tenantOperatorCode);
        model.addAttribute("elecStationList", elecStationList);
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/acct/acctBillOrderOperator";
    }


    /**
     * 跳转分销商收益明细(详情页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctBillOrder/{billOrderId}", method = RequestMethod.GET)
    public String detailAcctBillOrder(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectAcctBillOrder(billOrderId);
        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")) {
            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
        }
        List<AcctSubItem> acctSubItems = acctSubItemService.listAcctSubitem(billOrderId);
        if (acctSubItems == null || acctSubItems.size() == 0) {
            model.addAttribute("acctSubItems", null);
        } else {
            model.addAttribute("acctSubItems", acctSubItems);
        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
        return "/templates/acct/detailAcctBillOrder";
    }

    /**
     * 跳转分销商补充账单收益明细(详情页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailSupplyAcctBillOrder/{billOrderId}", method = RequestMethod.GET)
    public String detailSupplyAcctBillOrder(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectSupplyAcctBillOrder(billOrderId);
//        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")){
//            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
//        }
//        List<AcctSubItem> acctSubItems=acctSubItemService.listAcctSubitem(billOrderId);
//        if (acctSubItems==null||acctSubItems.size()==0){
//            model.addAttribute("acctSubItems",null);
//        }else {
//            model.addAttribute("acctSubItems",acctSubItems);
//        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("acctSubItems", null);
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
        return "/templates/acct/detailAcctBillOrder";
    }

    /**
     * 批量下载对账单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctBillOrders/{billOrderId}", method = RequestMethod.GET)
    @ResponseBody
    public TResponse detailAcctBillOrders(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectAcctBillOrder(billOrderId);
        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")) {
            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
        }
        List<AcctSubItem> acctSubItems = acctSubItemService.listAcctSubitem(billOrderId);
        if (acctSubItems == null || acctSubItems.size() == 0) {
            model.addAttribute("acctSubItems", null);
        } else {
            model.addAttribute("acctSubItems", acctSubItems);
        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
//        return "/templates/acct/detailAcctBillOrder";
        return TResponse.SUCCESS_DATA(model);
    }

    /**
     * 跳转分销商收益明细(详情页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctBillOrderOperator/{billOrderId}", method = RequestMethod.GET)
    public String detailAcctBillOrderOperator(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectAcctBillOrder(billOrderId);
        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")) {
            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
        }
        List<AcctSubItem> acctSubItems = acctSubItemService.listAcctSubitem(billOrderId);
        if (acctSubItems == null || acctSubItems.size() == 0) {
            model.addAttribute("acctSubItems", null);
        } else {
            model.addAttribute("acctSubItems", acctSubItems);
        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
        return "/templates/acct/detailAcctBillOrderOperator";
    }

    /**
     * 跳转分销商收益明细(详情页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailSupplyAcctBillOrderOperator/{billOrderId}", method = RequestMethod.GET)
    public String detailSupplyAcctBillOrderOperator(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectSupplyAcctBillOrder(billOrderId);
//        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")) {
//            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
//        }
//        List<AcctSubItem> acctSubItems = acctSubItemService.listAcctSubitem(billOrderId);
//        if (acctSubItems == null || acctSubItems.size() == 0) {
//            model.addAttribute("acctSubItems", null);
//        } else {
//            model.addAttribute("acctSubItems", acctSubItems);
//        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("acctSubItems", null);
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
        return "/templates/acct/detailAcctBillOrderOperator";
    }

    /**
     * 分销商批量下载对账单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctBillOrderOperators/{billOrderId}", method = RequestMethod.GET)
    @ResponseBody
    public TResponse detailAcctBillOrderOperators(@PathVariable("billOrderId") Long billOrderId, Model model) throws ParseException {
        AcctBillOrderResultVo acctBillOrderResultVo = acctBillOrderService.selectAcctBillOrder(billOrderId);
        if (acctBillOrderResultVo.getServiceAcctRule().contains("咨询订单金额")) {
            acctBillOrderResultVo.setConsultOrderAmount(acctBillOrderResultVo.getConsultAmount());
        }
        List<AcctSubItem> acctSubItems = acctSubItemService.listAcctSubitem(billOrderId);
        if (acctSubItems == null || acctSubItems.size() == 0) {
            model.addAttribute("acctSubItems", null);
        } else {
            model.addAttribute("acctSubItems", acctSubItems);
        }
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectOperatorStationId(acctBillOrderResultVo.getElecStationId(), acctBillOrderResultVo.getTenantOperatorCode());
        if (tenantOperatorStation == null) {
            model.addAttribute("acctContractList", null);
        } else {
            List<AcctContract> acctContractList = acctContractService.listAcctContract(tenantOperatorStation.getOperatorStationId());
            model.addAttribute("acctContractList", acctContractList);
        }
        TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctBillOrderResultVo.getTenantOperatorCode());
        model.addAttribute("tenantOperator", tenantOperator);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        model.addAttribute("acctBillOrderResultVo", acctBillOrderResultVo);
//        return "/templates/acct/detailAcctBillOrderOperator";
        return TResponse.SUCCESS_DATA(model);
    }

    /**
     * 跳转分销商结算总览(订单页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctDetail", method = RequestMethod.GET)
    public String acctDetail(Model model) {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        List<TenantOperator> tenantOperatorList = tenantOperatorService.listOperatorByTenantCode(tenantUser.getTenantCode());
        model.addAttribute("tenantOperatorList", tenantOperatorList);
        return "/templates/acct/acctDetail";
    }

    /**
     * 跳转分销商收益明细(订单页面)
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/orderAcctBillOrder/{billOrderId}", method = RequestMethod.GET)
    public String orderAcctBillOrder(@PathVariable("billOrderId") Long billOrderId, Model model) {
        AcctBillOrder acctBillOrder = acctBillOrderService.selectByPrimaryKey(billOrderId);
        model.addAttribute("acctBillOrder", acctBillOrder);
        return "/templates/acct/orderAcctBillOrder";
    }

    /**
     * 返回订单列表数据
     *
     * @return
     */
    @RequestMapping(value = "/listOrderAcctBillOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listOrderInfo(OrderAcctBillOrderSearch orderSearch) {
        PageInfo<OrderResult> pageInfo = acctBillOrderService.listPageByCondition(orderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 导出账单订单列表
     */
    @ResponseBody
    @RequestMapping("/exportOrderAcctBillOrder")
    public TResponse exportOrderAcctBillOrder(OrderAcctBillOrderSearch orderSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");
        try {

            logger.info(orderSearch.getTenantCode() + ",orderInfo/exportOrderInfo,startTime:{},endTime:{},count:{}",
                    orderSearch.getStartTime(), orderSearch.getEndTime(), orderSearch.getCount());

            ExportUtils.setDefaultPaging(orderSearch);
            List<OrderPrintVo> list = acctBillOrderService.exportOrderInfo(orderSearch);

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("订单列表", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OrderPrintVo.class).sheet("订单列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出订单失败", e.getMessage());
            return TResponse.FAIL(e.getMessage());
        }
    }


    /**
     * 获取分销商桩群
     *
     * @return
     */
    @RequestMapping(value = "/ListElecStation", method = RequestMethod.GET)
    @ResponseBody
    public TResponse ListElecStation(String tenantOperatorCode) {
        try {
            List<ElecStationResult> elecStationResultList = tenantOperatorStationService.listElecStationByTenantOperator(tenantOperatorCode);
            return TResponse.SUCCESS_DATA(elecStationResultList);
        } catch (Exception e) {
            logger.error("获取分销商桩群失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存审核分销商账单明细
     *
     * @return
     */
    @RequestMapping(value = "/saveReviewAcctBillOrder", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveReviewAcctBillOrder(AcctBillOrder acctBillOrder) {
        try {
            //acctBillOrder.setStatus("1");
            if ("1".equals(acctBillOrder.getStatus())) {
                acctBillOrder.setPushTime(new Date());
                if (acctBillOrder.getAdjustElecAmount() != null && acctBillOrder.getAdjustServiceAmount() != null) {
                    acctBillOrder.setFactAmount(matchNull(acctBillOrder.getAdjustElecAmount()).add(matchNull(acctBillOrder.getAdjustServiceAmount())).add(matchNull(acctBillOrder.getBillTotalMoney())));
                } else {
                    acctBillOrder.setFactAmount(acctBillOrder.getBillTotalMoney());
                }
            } else if ("2".equals(acctBillOrder.getStatus())) {
                BigDecimal zero = new BigDecimal(0);
                acctBillOrder.setFactAmount(zero);
                acctBillOrder.setAdjustElecAmount(zero);
                acctBillOrder.setAdjustServiceAmount(zero);
                if (acctBillOrder.getRejectRemark()!=null&&acctBillOrder.getRejectRemark()!=""){
                    acctBillOrder.setRejectRemark(acctBillOrder.getRejectRemark());
                }
            } else if ("3".equals(acctBillOrder.getStatus())) {
                if (acctBillOrder.getAcctRuleId() == null) {
                    acctBillOrder.setFactAmount(matchNull(acctBillOrder.getAdjustElecAmount()).add(matchNull(acctBillOrder.getAdjustServiceAmount())).add(matchNull(acctBillOrder.getBillTotalMoney())));
                }
            }
            acctBillOrderService.updateForStatus(acctBillOrder);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存审核分销商对账单失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    public BigDecimal matchNull(BigDecimal o) {
        return o == null ? BigDecimal.ZERO : o;

    }

    /**
     * 获取分销商收益明细列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctBillOrder", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctBillOrder(AcctBillOrderSearch acctBillOrderSearch) {
        PageInfo<AcctBillOrderResultVo> pageInfo = acctBillOrderService.listPageAcctBillOrder(acctBillOrderSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转分销商桩群合同页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctContract/{operatorStationId}", method = RequestMethod.GET)
    public String acctContract(@PathVariable("operatorStationId") Long operatorStationId, Model model) {
        TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectByPrimaryKey(operatorStationId);
        model.addAttribute("tenantOperatorStation", tenantOperatorStation);
        model.addAttribute("contractPath", upYunConfig.getDownloadRoot());
        return "/templates/acct/acctContract";
    }

    /**
     * 获取分销商桩群合同数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctContract", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctContract(BaseSearch baseSearch, Long operatorStationId) {
        PageInfo<AcctContract> pageInfo = acctContractService.listPageAcctContract(baseSearch, operatorStationId);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 保存分销商桩群合同
     *
     * @return
     */
    @RequestMapping(value = "/saveAcctContract", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctContract(AcctContract acctContract, @RequestParam(value = "file") MultipartFile file) {
        try {
            if (StringUtil.isBlank(acctContract.getContractName())) {
                return TResponse.FAIL("请填写合同名称");
            }
            if (file.getSize() == 0) {
                return TResponse.FAIL("请上传文件");
            }

            String fileName = file.getOriginalFilename();
            String fileNameEndName = fileName.substring(fileName.length() - 3, fileName.length());
            if (!"pdf".equals(fileNameEndName) && !"jpg".equals(fileNameEndName) && !"png".equals(fileNameEndName)) {
                return TResponse.FAIL("仅支持上传pdf，jpg，png格式文件");
            }
            TenantUser tenantUser = ShiroUtils.getSessionUser();
            WebUploader webUploader = WebUploader.getInstance(upYunConfig);
            String filePath = uploadImg.uploadFile(tenantUser.getTenantCode(), webUploader, file, upYunConfig.getUploadAcctContractPath());
            logger.info("上传合同路径:{}", filePath);
            TenantOperatorStation tenantOperatorStation = tenantOperatorStationService.selectByPrimaryKey(acctContract.getOperatorStationId());
            if (tenantOperatorStation == null) {
                return TResponse.FAIL("不存在此分销商桩群");
            }

            acctContract.setTenantCode(tenantOperatorStation.getTenantCode());
            acctContract.setTenantOperatorCode(tenantOperatorStation.getTenantOperatorCode());
            acctContract.setOperatorStationId(tenantOperatorStation.getOperatorStationId());
            acctContract.setContractName(acctContract.getContractName());
            acctContract.setContractPdf(filePath);
            acctContractService.insertSelective(acctContract);

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商桩群合同失败", e);
            return TResponse.FAIL("操作失败");
        }
    }

    /**
     * 删除结算合同
     */
    @ResponseBody
    @RequestMapping(value = "/deleteAcctContract", method = RequestMethod.POST)
    public TResponse deleteAcctContract(Long contractId) {
        try {
            AcctContract acctContract = new AcctContract();
            acctContract.setContractId(contractId);
            acctContract.setIsDelete("1");
            logger.info("删除分销商合同ID:{}", contractId);
            acctContractService.updateByPrimaryKeySelective(acctContract);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("删除结算合同失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 下载合同文件
     *
     * @return
     */
    @RequestMapping(value = "/AcctContractDownload", method = RequestMethod.GET)
    @ResponseBody
    public TResponse AcctContractDownload(String contractPdf, String contractName, HttpServletResponse response) {
        try {

            String fileNameEndName = contractPdf.substring(contractPdf.length() - 4, contractPdf.length());
            String imgPath = upYunConfig.getDownloadRoot() + contractPdf;
            URL url = new URL(imgPath);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            OutputStream fileOutputStream = response.getOutputStream();
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            response.reset();
            response.setContentType("application/octet-stream");
            response.setCharacterEncoding("UTF-8");

            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(contractName, "UTF-8") + fileNameEndName);
            response.setHeader("Set-Cookie", "fileDownload=true; path=/");
            // response.setHeader("Content-disposition", "attachment; filename=" + (imgPath.substring(imgPath.lastIndexOf("/") + 1, imgPath.length())));

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();

            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商桩群合同失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 跳转分销商提现审核页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctWithdrawApply", method = RequestMethod.GET)
    public String acctWithdrawApply(Model model) {
        return "/templates/acct/acctWithdrawApply";
    }


    /**
     * 更改审核状态
     */
    @ResponseBody
    @RequestMapping(value = "/updateAcctWithdrawApplyStatus", method = RequestMethod.POST)
    public TResponse updateAcctWithdrawApplyStatus(Long withdrawApplyId, String status, String remark) {
        try {
            TResponse tResponse = TResponse.SUCCESS();
            if ("2".equals(status)) {

                if (StringUtil.isBlank(remark)) {
                    tResponse = TResponse.FAIL("请输入驳回备注");
                }

                AcctWithdrawApply acctWithdrawApply = new AcctWithdrawApply();
                acctWithdrawApply.setStatus(status);
                acctWithdrawApply.setWithdrawApplyId(withdrawApplyId);
                acctWithdrawApply.setRemark(remark);
                acctWithdrawApplyService.updateStatusForFail(acctWithdrawApply);
            } else {
                AcctWithdrawApply acctWithdrawApply = acctWithdrawApplyService.selectByPrimaryKey(withdrawApplyId);
//                if (StringUtil.isBlank(acctWithdrawApply.getAlipayUserId())) {
//                    tResponse = TResponse.FAIL("请使用支付宝进行提现");
//                    return tResponse;
//                }
                //提现到支付宝
                //分销商 888888889
                TenantOperator tenantOperator = tenantOperatorService.selectByPrimaryKey(acctWithdrawApply.getTenantOperatorCode());
                if (StringUtil.isNotBlank(acctWithdrawApply.getAlipayUserId())) {
                    AlipayTransPayWalletVo alipayTransPayWalletVo = new AlipayTransPayWalletVo();
                    //收款账户类型,0 对公（在金融机构开设的公司账户）,如果银行卡为对公，必须传递省市支行信息或者联行号 1对私（在金融机构开设的个人账户）
//                alipayTransPayWalletVo.setAccountType("0");
//                alipayTransPayWalletVo.setAlipayUserId("hpccbd3956@sandbox.com");
                    alipayTransPayWalletVo.setAccountType("1");

                    //提现类型 0平台转帐 1网银转帐 默认0
                    alipayTransPayWalletVo.setWithdrawType("0");

                    //申请来源 0运营商后台  默认0
                    alipayTransPayWalletVo.setApplySource("0");

                    //提现途径 0支付宝 1网银 默认0
                    alipayTransPayWalletVo.setWithdrawBy("0");
                    alipayTransPayWalletVo.setAlipayUserId(acctWithdrawApply.getAlipayUserId());
                    alipayTransPayWalletVo.setAlipayUserName(acctWithdrawApply.getAlipayUserName());
//                    alipayTransPayWalletVo.setAlipayUserId("455322144@qq.com");
//                    alipayTransPayWalletVo.setAlipayUserName("张文博");
                    // 提现金额
//                    alipayTransPayWalletVo.setTransAmount(new BigDecimal(1));
                    alipayTransPayWalletVo.setTransAmount(acctWithdrawApply.getWithdrawAmount());
                    alipayTransPayWalletVo.setWithdrawApplyId(withdrawApplyId);
                    tResponse = aliPayWalletService.transPayWallet(null, tenantOperator, alipayTransPayWalletVo, new TenantOperatorAcctSetting());
                } else {
                    //提现到银行卡(暂定)
                    tResponse = tenantOperatorService.bankTransPayWallet(tenantOperator, acctWithdrawApply, new TenantOperatorAcctSetting());
                }
            }
            return tResponse;
        } catch (Exception e) {
            logger.error("更改审核状态失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }

    /**
     * 跳转分销商提现详情页面
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/detailAcctWithdrawApply/{withdrawApplyId}", method = RequestMethod.GET)
    public String detailAcctWithdrawApply(@PathVariable("withdrawApplyId") Long withdrawApplyId, Model model) {
        AcctWithdrawApplyResult acctWithdrawApply = acctWithdrawApplyService.selectAcctWithdrawApply(withdrawApplyId);
        model.addAttribute("acctWithdrawApply", acctWithdrawApply);
        return "/templates/acct/detailAcctWithdrawApply";
    }


    /**
     * 获取分销商申请列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageAcctWithdrawApply", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageAcctWithdrawApply(AcctWithdrawApplySearch acctBankSearch) {
        PageInfo<AcctWithdrawApplyResult> pageInfo = acctWithdrawApplyService.listPageAcctWithdrawApply(acctBankSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 获取分销商钱包数据
     */
    @ResponseBody
    @RequestMapping(value = "/tenantOperatorAccountData", method = RequestMethod.GET)
    public TResponse tenantOperatorAccountData(String tenantOperatorCode) {
        try {
            BigDecimal unconfirmedAmount = acctBillOrderService.sumUnconfirmedAmount(tenantOperatorCode);
            BigDecimal withdrawWaitAmount = acctWithdrawApplyService.sumWithdrawWaitAmount(tenantOperatorCode);
            TenantOperatorAccount tenantOperatorAccount = tenantOperatorAccountService.selectByPrimaryKey(tenantOperatorCode);
            //todo 更改需求此处作废
            //if (tenantOperatorAccount == null) {
            //    logger.info("不存在分销商钱包数据,生成:{tenantOperatorCode}");
            //    TenantUser tenantUser = ShiroUtils.getSessionUser();
            //    TenantOperatorAccount newAccount = new TenantOperatorAccount();
            //    newAccount.setTenantCode(tenantUser.getTenantCode());
            //    newAccount.setTenantOperatorCode(tenantOperatorCode);
            //    tenantOperatorAccountService.insertSelective(newAccount);
            //}
            if (StringUtil.isBlank(tenantOperatorCode)) {
                tenantOperatorAccount = tenantOperatorAccountService.sumOperatorAccount();
            }
            tenantOperatorAccount.setUnconfirmedAmount(unconfirmedAmount);
            tenantOperatorAccount.setWithdrawWaitAmount(withdrawWaitAmount);
            return TResponse.SUCCESS_DATA(tenantOperatorAccount);
        } catch (Exception e) {
            logger.error("获取分销商钱包数据失败", e);
            return TResponse.FAIL("更新状态失败");
        }
    }


    /**
     * 获取分销商订单统计数据
     */
    @ResponseBody
    @RequestMapping(value = "/tenantOperatorOrderData", method = RequestMethod.GET)
    public TResponse tenantOperatorOrderData(Long stationId, String startTime, String endTime, String tenantOperatorCode) {
        try {
            TenantOperatorOrderDataVo tenantOperatorOrderDataVo = acctBillOrderService.sumTenantOperatorOrderData(stationId, startTime, endTime, tenantOperatorCode);
            return TResponse.SUCCESS_DATA(tenantOperatorOrderDataVo);
        } catch (Exception e) {
            logger.error("获取分销商钱包数据失败", e);
            return TResponse.FAIL("获取分销商订单统计数据失败");
        }
    }

    /**
     * 获取分销商订单统计数据(EChar)
     */
    @ResponseBody
    @RequestMapping(value = "/tenantOperatorOrderECharData", method = RequestMethod.GET)
    public TResponse tenantOperatorOrderECharData(Long stationId, String startTime, String endTime, String tenantOperatorCode) {
        try {
            List<TenantOperatorOrderDataECharVo> tenantOperatorOrderDataECharVo = acctBillOrderService.sumTenantOperatorOrderECharData(stationId, startTime, endTime, tenantOperatorCode);
            return TResponse.SUCCESS_DATA(tenantOperatorOrderDataECharVo);
        } catch (Exception e) {
            logger.error("获取分销商钱包数据失败(EChar)", e);
            return TResponse.FAIL("获取分销商订单统计数据(EChar)失败");
        }
    }

    /**
     * 结算中心数据汇总
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/tenantOperatorTotalData", method = RequestMethod.GET)
    public TResponse tenantOperatorTotalData() {
        TenantUser tenantUser = ShiroUtils.getSessionUser();
        try {
            AcctTotalDataVo acctTotalDataVo = new AcctTotalDataVo();
            //分销商站点总数
            int totalStationCount = tenantOperatorStationService.countByOperatorStation(tenantUser.getTenantCode());
            //分销商设置了结算规则站点数量
            int acctRuleStationCount = acctRuleService.countByAcctRuleStation(tenantUser.getTenantCode());
            //本月已产生账单数量
            int generatedOrderCount = acctBillOrderService.countByGeneratedOrder(tenantUser.getTenantCode());
            //本月未产生账单数量

            //待审核账单数量
            int notReviewedOrderCount = acctBillOrderService.countByNotReviewedOrder(tenantUser.getTenantCode());

            AcctBillOrderExample example = new AcctBillOrderExample();
            example.createCriteria().andStatusEqualTo("1").andTenantCodeEqualTo(tenantUser.getTenantCode());
            //待确认账单数量
            int unConfirmedOrderCount = (int) acctBillOrderService.countByExample(example);
            //待审核提现申请数量
            int notReviewedWithdrowApplyOrderCount = acctWithdrawApplyService.countByNotReviewedWithdrowApplyOrder(tenantUser.getTenantCode());
            //待补票账单数量
            int notPaidOrderCount = acctWithdrawApplyService.countByNotPaidOrder(tenantUser.getTenantCode());

            acctTotalDataVo.setAcctRuleStationCount(acctRuleStationCount);
            acctTotalDataVo.setStationCount(totalStationCount - acctRuleStationCount);
            acctTotalDataVo.setGeneratedOrderCount(generatedOrderCount);
            acctTotalDataVo.setNotReviewedOrderCount(notReviewedOrderCount);
            acctTotalDataVo.setNotReviewedWithdrowApplyOrderCount(notReviewedWithdrowApplyOrderCount);
            acctTotalDataVo.setUnConfirmedOrderCount(unConfirmedOrderCount);
            acctTotalDataVo.setNotPaidOrderCount(notPaidOrderCount);
            return TResponse.SUCCESS_DATA(acctTotalDataVo);
        } catch (Exception e) {
            logger.error("获取结算中心数据汇总失败", e);
            return TResponse.FAIL("获取结算中心数据汇总失败");
        }
    }


    /**
     * 获取分销商结算完成的订单
     */
    @ResponseBody
    @RequestMapping(value = "/listAcctBillOrderForComplete", method = RequestMethod.GET)
    public TResponse listAcctBillOrderForComplete(String tenantOperatorCode) {
        try {
            List<AcctBillOrderResultVo> acctBillOrderResultVos = acctBillOrderService.listAcctBillOrderForComplete(tenantOperatorCode);
            return TResponse.SUCCESS_DATA(acctBillOrderResultVos);
        } catch (Exception e) {
            logger.error("获取分销商结算完成的订单失败", e);
            return TResponse.FAIL("获取分销商结算完成的订单失败");
        }
    }


    /**
     * 跳转分销商余额变动记录
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/tenantOperatorAccountRecord/{tenantOperatorCode}", method = RequestMethod.GET)
    public String tenantOperatorAccountRecord(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        return "/templates/acct/tenantOperatorAccountRecord";
    }

    /**
     * 获取分销商余额变动记录列表数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listPageTenantOperatorAccountRecord", method = RequestMethod.GET)
    @ResponseBody
    public WebPageInfo listPageTenantOperatorAccountRecord(TenantOperatorAccountRecordSearch acctBankSearch) {
        PageInfo<TenantOperatorAccountRecordResultVo> pageInfo = tenantOperatorAccountRecordService.listPageTenantOperatorAccountRecord(acctBankSearch);
        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
        return webPageInfo;
    }


    /**
     * 跳转分销商提现申请记录
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/acctWithdrawApplyByOperator/{tenantOperatorCode}", method = RequestMethod.GET)
    public String acctWithdrawApplyByOperator(@PathVariable("tenantOperatorCode") String tenantOperatorCode, Model model) {
        List<ElecStationResult> elecStationResultList = tenantOperatorStationService.listElecStationByTenantOperator(tenantOperatorCode);
        model.addAttribute("tenantOperatorCode", tenantOperatorCode);
        model.addAttribute("elecStationResultList", elecStationResultList);
        return "/templates/acct/acctWithdrawApplyByOperator";
    }

    /**
     * 获取查看发票数据数据
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/listAcctWithdrawInvoice", method = RequestMethod.GET)
    @ResponseBody
    public List<AcctWithdrawInvoice> listAcctWithdrawInvoice(Long withdrawApplyId) {
        return acctWithdrawInvoiceService.listInvoiceByApplyId(withdrawApplyId);
    }


//    /**
//     * 获取分销商提现申请列表数据
//     *
//     * @param
//     * @return
//     */
//    @RequestMapping(value = "/listPageAcctWithdrawApplyByOperator", method = RequestMethod.GET)
//    @ResponseBody
//    public WebPageInfo listPageAcctWithdrawApplyByOperator(AcctBankSearch acctBankSearch) {
//        PageInfo<AcctBankResultVo> pageInfo = acctBankService.listPageAcctBank(acctBankSearch);
//        WebPageInfo webPageInfo = new WebPageInfo(pageInfo.getList(), Long.valueOf(pageInfo.getTotal()).intValue());
//        return webPageInfo;
//    }


    /**
     * 保存分销商提现申请
     *
     * @return
     */
    @RequestMapping(value = "/saveAcctWithdrawApply", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctWithdrawApply(AcctWithdrawApply acctWithdrawApply, String acctBillOrderList, String invoiceList) {
        try {
            if (BeanUtil.isValid(acctWithdrawApply.getAcctBankAccount(), acctWithdrawApply.getAlipayUserId())) {
                return TResponse.FAIL("请选择提现途径");
            }
            // AcctWithdrawApply apply = JSON.parseObject(acctWithdrawApply, AcctWithdrawApply.class);
            List<Long> orderIds = JSON.parseArray(acctBillOrderList, Long.class);
            if (CollectionUtils.isEmpty(orderIds)) {
                return TResponse.FAIL("请选择结算单");
            }
            List<String> invoicePathList = JSON.parseArray(invoiceList, String.class);
//            acctWithdrawApply.setWithdrawAmount(acctWithdrawApply.getWithdrawElecAmount().add(acctWithdrawApply.getWithdrawServiceAmount()));
//            TenantOperatorAcctSettingExample example=new TenantOperatorAcctSettingExample();
//            example.createCriteria().andTenantOperatorCodeEqualTo(acctWithdrawApply.getTenantOperatorCode());
//            TenantOperatorAcctSetting tenantOperatorAcctSetting=tenantOperatorAcctSettingService.selectByExample(example).get(0);
//            //设置了自动体现审核的将审核状态设置成已处理
//            if ("1".equals(tenantOperatorAcctSetting.getWithdrawAudit())){
//                acctWithdrawApply.setStatus("1");
//            }
            acctWithdrawApplyService.saveAcctWithdrawApply(acctWithdrawApply, orderIds, invoicePathList);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("保存分销商桩群合同失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 保存分销商提现申请发票PDF
     *
     * @return
     */
    @RequestMapping(value = "/saveInvoicePDF", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveInvoicePDF(@RequestParam(value = "file") MultipartFile file) {
        try {

            if (file.getSize() == 0) {
                return TResponse.FAIL("请上传文件");
            }

            String fileName = file.getOriginalFilename();
            String fileEndName = fileName.substring(fileName.length() - 3, fileName.length());

            if (!"pdf".equals(fileEndName) && !"jpg".equals(fileEndName) && !"png".equals(fileEndName)) {
                return TResponse.FAIL("仅支持上传pdf，jpg，png格式文件");
            }

            TenantUser tenantUser = ShiroUtils.getSessionUser();
            WebUploader webUploader = WebUploader.getInstance(upYunConfig);
            String filePath = uploadImg.uploadFile(tenantUser.getTenantCode(), webUploader, file, upYunConfig.getUploadOperatorInvoicePath());
            logger.info("上传合同PDF路径:{}", filePath);
            return TResponse.SUCCESS_DATA(upYunConfig.getDownloadRoot() + "," + filePath);
        } catch (Exception e) {
            logger.error("保存分销商提现申请发票PDF失败", e);
            return TResponse.FAIL("操作失败");
        }
    }


    /**
     * 导出分销商提现审核
     */
    @ResponseBody
    @RequestMapping("/exportAcctWithdrawApply")
    public TResponse exportAcctWithdrawApply(AcctWithdrawApplySearch acctWithdrawApplySearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        try {
            ExportUtils.setDefaultPaging(acctWithdrawApplySearch);
            List<AcctWithdrawApplyResult> list = acctWithdrawApplyService.listExportAcctWithdrawApply(acctWithdrawApplySearch);
            logger.info(acctWithdrawApplySearch.getTenantCode() + ",acctTenantOperator/exportAcctWithdrawApply");

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分销商提现审核", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AcctWithdrawApplyResult.class).sheet("分销商提现审核列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出提现申请记录失败", e);
            return TResponse.FAIL("操作失败");
        }

    }


    /**
     * 导出分销商站点列表
     */
    @ResponseBody
    @RequestMapping("/exportAcctTenantOperatorElecStation")
    public TResponse exportAcctTenantOperatorElecStation(AcctTenantOperatorElecStationSearch acctTenantOperatorElecStationSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        try {
            ExportUtils.setDefaultPaging(acctTenantOperatorElecStationSearch);
            List<OperatorElecStationVo> list = tenantOperatorService.exportAcctTenantOperatorElecStation(acctTenantOperatorElecStationSearch);
            logger.info(acctTenantOperatorElecStationSearch.getTenantCode() + ",acctTenantOperator/exportAcctTenantOperatorElecStation");

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分销商站点", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), OperatorElecStationVo.class).sheet("分销商站点列表").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出分销商站点列表失败", e);
            return TResponse.FAIL("操作失败");
        }

    }


    /**
     * 导出账单明细
     */
    @ResponseBody
    @RequestMapping("/exportAcctBillOrder")
    public TResponse exportAcctBillOrder(AcctBillOrderSearch acctBillOrderSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        try {
            ExportUtils.setDefaultPaging(acctBillOrderSearch);
            List<AcctBillOrderResultVo> list = acctBillOrderService.exportAcctBillOrder(acctBillOrderSearch);
            logger.info(acctBillOrderSearch.getTenantCode() + ",acctTenantOperator/exportAcctTenantOperatorElecStation");

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("对账单", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), AcctBillOrderResultVo.class).sheet("对账单").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出对账单失败", e);
            return TResponse.FAIL("操作失败");
        }

    }

    /**
     * 导出分销商余额变动记录
     */
    @ResponseBody
    @RequestMapping("/exportTenantOperatorAccountRecord")
    public TResponse exportTenantOperatorAccountRecord(TenantOperatorAccountRecordSearch acctBillOrderSearch, HttpServletResponse response) {
        response.setHeader("Set-Cookie", "fileDownload=true; path=/");

        try {
            ExportUtils.setDefaultPaging(acctBillOrderSearch);
            List<TenantOperatorAccountRecordResultVo> list = tenantOperatorAccountRecordService.exportTenantOperatorAccountRecord(acctBillOrderSearch);
            logger.info(acctBillOrderSearch.getTenantCode() + ",acctTenantOperator/exportAcctTenantOperatorElecStation");

            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("分销商余额变动记录", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
            EasyExcel.write(response.getOutputStream(), TenantOperatorAccountRecordResultVo.class).sheet("分销商余额变动记录").doWrite(list);
            return TResponse.SUCCESS();
        } catch (Exception e) {
            logger.error("导出分销商余额变动记录失败", e);
            return TResponse.FAIL("操作失败");
        }

    }

    /**
     * 保存补充账单
     *
     * @param acctBillOrder
     * @return
     */
    @RequestMapping(value = "/saveAcctBillOrder", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveAcctBillOrder(AcctBillOrder acctBillOrder) {
//        if (BeanUtil.isValid(acctBillOrder.getBillStartTime(),acctBillOrder.getBillEndTime(),acctBillOrder.getBillTotalElecMoney(),acctBillOrder.getBillTotalSeviceMoney(),acctBillOrder.getBillTotalMoney())){
//            return TResponse.FAIL("请填写指定的参数");
//        }
        if (acctBillOrder.getBillStartTime() == null || acctBillOrder.getBillEndTime() == null) {
            return TResponse.FAIL("请填写指定的参数");
        }
        TenantOperatorAcctSettingExample example=new TenantOperatorAcctSettingExample();
        example.createCriteria().andTenantOperatorCodeEqualTo(acctBillOrder.getTenantOperatorCode());
        TenantOperatorAcctSetting tenantOperatorAcctSetting=tenantOperatorAcctSettingService.selectByExample(example).get(0);
        if ("1".equals(tenantOperatorAcctSetting.getPushMethod())){
            acctBillOrder.setStatus("1");
            acctBillOrder.setPushTime(new Date());
        }
        acctBillOrderService.saveAcctBillOrder(acctBillOrder);
        return TResponse.SUCCESS();
    }

    /**
     * 查询分销商结算设置
     * @param tenantOperatorCode
     * @return
     */
    @RequestMapping(value = "/selectTenantOperatorAcctSetting",method = RequestMethod.GET)
    @ResponseBody
    public TResponse selectTenantOperatorAcctSetting(String tenantOperatorCode){
        TenantOperatorAcctSettingExample example=new TenantOperatorAcctSettingExample();
        example.createCriteria().andTenantOperatorCodeEqualTo(tenantOperatorCode);
        TenantOperatorAcctSetting tenantOperatorAcctSetting=tenantOperatorAcctSettingService.selectByExample(example).get(0);
        return TResponse.SUCCESS_DATA(tenantOperatorAcctSetting);
    }

    /**
     * 保存分销商结算设置
     *
     * @param tenantOperatorAcctSetting
     * @return
     */
    @RequestMapping(value = "/saveTenantOperatorAcctSetting", method = RequestMethod.POST)
    @ResponseBody
    public TResponse saveTenantOperatorAcctSetting(TenantOperatorAcctSetting tenantOperatorAcctSetting) {
        //查询分销商设置的结算配置
        TenantOperatorAcctSettingExample example = new TenantOperatorAcctSettingExample();
        example.createCriteria().andTenantOperatorCodeEqualTo(tenantOperatorAcctSetting.getTenantOperatorCode());
        List<TenantOperatorAcctSetting> tenantOperatorAcctSettings = tenantOperatorAcctSettingService.selectByExample(example);
        if (tenantOperatorAcctSettings.size() > 0 && tenantOperatorAcctSettings != null) {
            tenantOperatorAcctSettingService.updateTenantOperatorAcctSetting(tenantOperatorAcctSetting);
            return TResponse.SUCCESS();
        } else {
            return TResponse.FAIL("该分销商的桩群还未设置规则，请先设置规则");
        }
    }
}
